<template>
  <div>
    <el-breadcrumb separator-class='el-icon-arrow-right'>
      <el-breadcrumb-item v-bind:to='{ path: "/" }'>首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>内部员工管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class='dict-main'>
      <el-tabs v-model='activeName'  class='title-top'>
        <el-tab-pane label='内部员工管理' name='operator'>
          <div class='main-module'>
            <div class='btn-module'>
              <el-button  size='small' @click='openAdd'  type='primary' icon='el-icon-plus'>新增</el-button>
            </div>
            <el-table :data='members' stripe style='width: 100%'>
              <el-table-column  label='登录账号' prop='userId' align='center'></el-table-column>
              <el-table-column  label='用户名称' prop='userName' align='center' ></el-table-column>
              <el-table-column  label='联系电话' prop='mobile' align='center'></el-table-column>
              <el-table-column  label='联系邮箱' prop='email' align='center'></el-table-column>
              <el-table-column  label='用户状态' align='center' >
                <template scope='scope'>
                  {{scope.row.status===0?'禁用':'启用'}}</template>
              </el-table-column>

              <el-table-column label='操作' fixed='right' width='270' align='center' >
                <template slot-scope='scope'>
                  <el-button size='mini' type='primary' @click='openUpdate(scope.row)' >修改</el-button>
                  <el-button size='mini' type='success'  @click='updateStatus(scope.row)' v-if='scope.row.status===0' >启用</el-button>
                  <el-button size='mini' type='danger'  @click='updateStatus(scope.row)' v-else >禁用</el-button>
                  <el-button size='mini' type='warning'  @click='openResetPassword(scope.row)' >重置密码</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--分页-->
            <div class='block text-center'>
              <el-pagination @size-change='handleSizeChange' @current-change='handleCurrentChange' :current-page='pageable.currentPage' :page-sizes='[10, 20, 40, 80, 100]' :page-size='pageable.pageSize' layout='total, sizes, prev, pager, next, jumper' :total='pageable.total'></el-pagination>
            </div>


            <!-- 新增,修改弹窗-->
            <div>
              <el-dialog :title='textMap[dialogOption]' :visible.sync='dialogVisible'  width='70%' class='more-input-dialog' >
                <el-form  :model='memberForm' :rules='rules' ref='memberForm' label-width='100px'>
                  <el-form-item label='' prop='id'  style='display: none' >
                    <el-input  v-model='memberForm.id' ></el-input>
                  </el-form-item>
                  <el-form-item label='登录ID' prop='userId'>
                    <el-input placeholder='请输入登录ID,建议用英文' v-model='memberForm.userId' @blur='isExistUserId()' v-if='dialogOption=="create"'></el-input>
                    <el-input placeholder='请输入登录ID,建议用英文' v-model='memberForm.userId' readonly v-else></el-input>
                  </el-form-item>
                  <el-form-item label='登陆密码' prop='password' v-if='dialogOption=="create"'>
                    <el-input placeholder='请输入登陆密码,6-18位数字,字母组合' type='password' max='15' v-model='memberForm.password'></el-input>
                  </el-form-item>
                  <el-form-item label='确认密码' prop='passwords' v-if='dialogOption=="create"'>
                    <el-input placeholder='请输入登陆密码,6-18位数字,字母组合' type='password' max='15' v-model='memberForm.passwords'></el-input>
                  </el-form-item>
                  <el-form-item label='用户名' prop='userName'>
                    <el-input placeholder='请输入用户名' v-model='memberForm.userName'></el-input>
                  </el-form-item>
                  <el-form-item label='手机号码' prop='mobile'>
                    <el-input placeholder='请输入手机号码' type='tel' v-model='memberForm.mobile' v-on:blur='mobileExist()'></el-input>
                  </el-form-item>
                  <el-form-item label='邮箱' prop='email'>
                    <el-input placeholder='请输入邮箱'  v-model='memberForm.email'></el-input>
                  </el-form-item>
                  <el-form-item label='是否启用' prop='status' >
                    <el-radio-group v-model='memberForm.status'>
                      <el-radio :label='1'>启用</el-radio>
                      <el-radio :label='0'>禁用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label='所属角色' prop='roles'>
                    <el-select v-model='memberForm.roleIds' multiple placeholder='请选择'>
                      <el-option
                        v-for='item in roles'
                        :key='item.id'
                        :label='item.name'
                        :disabled="item.disabled"
                        :value='item.id'>
                      </el-option>
                    </el-select>
                  </el-form-item>

                </el-form>
                <div slot='footer' class='dialog-footer clear'>
                  <el-button @click='cancelAdd("memberForm")' >取 消</el-button>
                  <el-button :disabled='isDisable' v-if='dialogOption=="create"'  type='primary' @click='saveMember("memberForm")'>确 定</el-button>
                  <el-button :disabled='isDisable' type='primary' v-if='dialogOption=="update"' @click='updateMember("memberForm")' >确 定</el-button>
                </div>
              </el-dialog>
            </div>

            <!-- 新增,修改弹窗-->
            <div>
              <el-dialog :title='textMap[dialogOption]' :visible.sync='dialogPasswordVisible'  >
                <el-form label-width='100px' :rules='rulees' ref='formpas'  :model='formpas'>
                  <el-form-item label='' style='display: none' >
                    <el-input  v-model='formpas.resetPasswordMemberId' ></el-input>
                  </el-form-item>
                  <el-form-item label='新密码' prop='resetPassword'>
                    <el-input placeholder='请输入新密码' type='password' v-model='formpas.resetPassword'  ></el-input>
                  </el-form-item>
                  <el-form-item label='确认密码'  prop='resetPasswords'>
                    <el-input placeholder='请重新输入密码确认' type='password' v-model='formpas.resetPasswords' ></el-input>
                  </el-form-item>
                </el-form>
                <div slot='footer' class='dialog-footer'>
                  <el-button @click='cancelPassword()' >取 消</el-button>
                  <el-button :disabled='isDisable' type='primary' @click='savePassword()'>确 定</el-button>
                </div>
              </el-dialog>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
  </div>
</template>


<script>
import {
  queryMember,
  findAllRoles,
  findByUserId,
  insert,
  updateStatus,
  update,
  passwordReset,
  getMemberAccountByMobile
} from '@/api/operator';
import vail_ from '@/store/validation';
export default {
  data () {
    return {
      activeName: 'operator',
      resetPasswordMemberId: '',
      formpas: {
        resetPassword: '',
        resetPasswords: ''
      },
      roles: [],
      allRoles: [],
      isDisable: false,
      members: [],
      dialogVisible: false,
      dialogPasswordVisible: false,
      dialogOption: '',
      tableData: [],
      pageable: {
        currentPage: 1,
        pageSize: 10
      },
      passUserId: false,
      passUserIdMsg: '请输入登陆ID,建议用名称的英文!',
      passMobile: false,
      passMobileMsg: '请输入联系电话',
      updateMobile: '',
      textMap: {
        update: '员工编辑',
        create: '新增内部员工',
        password: '重置密码'
      },
      memberForm: {},
      rulees: {
        resetPassword: [
          {
            required: true,
            validator: vail_.validatePass,
            trigger: 'blur'
          }
        ],
        resetPasswords: [
          {
            required: true,
            validator: vail_.validatePassagin,
            trigger: 'blur'
          }
        ]
      },
      rules: {
        userId: [
          {
            required: true,
            message: '请输入登陆ID,建议用用户名的拼音',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符之间'
          }
        ],
        userName: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            validator: vail_.phonevailable,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            validator: vail_.emailvailable,
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            validator: vail_.validatePass,
            trigger: 'blur'
          }
        ],
        passwords: [
          {
            required: true,
            validator: vail_.validatePassagin,
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    mobileExist () {
      var _this = this;
      var mobile = _this.memberForm.mobile;
      if (!mobile || !/^[1][3,4,5,7,8,9][0-9]{9}$/.test(mobile)) {
        _this.passMobile = false;
        _this.passMobileMsg = '请输入正确的手机号码';
        return;
      }
      getMemberAccountByMobile(mobile).then(response => {
        if (response.code == 0 && response.data) {
          if (_this.dialogOption == 'create') {
            this.$message({
              message: response.message,
              type: 'error'
            });
            _this.passMobile = false;
            _this.passMobileMsg = response.message;
          }else{
            if(this.updateMobile == mobile){
              _this.passMobile = true;
              _this.passMobileMsg = '';
            }else{
              this.$message({
                message: response.message,
                type: 'error'
              });
              _this.passMobile = false;
              _this.passMobileMsg = response.message;
            }
          }
        }else{
          _this.passMobile = true;
          _this.passMobileMsg = '';
        }
      });
    },
    openResetPassword (row) {
      this.dialogOption = 'password';
      this.dialogPasswordVisible = true;
      this.resetPasswordMemberId = row.userId;
      this.formpas.resetPassword = '';
      this.formpas.resetPasswords = '';
    },
    cancelPassword () {
      this.dialogPasswordVisible = false;
      this.resetPasswordMemberId = '';
    },
    savePassword () {
      var _this = this;
      this.isDisable = true;
      setTimeout(() => {
        this.isDisable = false;
      }, 2000);
      this.$refs.formpas.validate(valid => {
        if (valid) {
          _this.formpas.resetPasswordMemberId = this.resetPasswordMemberId;
          passwordReset(
            _this.formpas.resetPasswordMemberId,
            _this.formpas.resetPassword
          ).then(response => {
            if (response.code == 0 && response.data) {
              this.$message({
                message: response.message,
                type: 'success'
              });
            }
            _this.cancelPassword();
          });
        } else {
          this.$message({
            message: '密码格式有误，请重新填写',
            type: 'error'
          });
        }
      });
    },
    cancelAdd () {
      this.dialogVisible = false;
    },
    handleSizeChange (val) {
      this.pageable.pageSize = val;
      this.refresh();
    },
    handleCurrentChange (val) {
      this.pageable.currentPage = val;
      this.refresh();
    },
    openUpdate (row) {
      var roles = [];
      var allRoles = this.allRoles;
      allRoles.forEach(function (a) {
        var b = {
          id: a.id,
          name: a.name,
          code: a.code,
          remark: a.remark,
          type: a.type
        };
        if(a.status != 1){
          b.disabled = true;
          b.name = a.name+'(禁用)';
        }
        roles.push(b);
      });
      this.roles = roles;
      this.updateMobile = row.mobile;
      this.memberForm = {
        id: row.id,
        userId: row.userId,
        userName: row.userName,
        mobile: row.mobile,
        email: row.email,
        status: row.status,
        roleIds: row.roleIds
      };
      this.dialogVisible = true;
      this.dialogOption = 'update';
    },
    updateMember (memberForm) {
      var _this = this;
      this.isDisable = true;
      setTimeout(() => {
        this.isDisable = false;
      }, 2000);
      if (_this.updateMobile != _this.memberForm.mobile) {
        _this.$message({
          message: _this.passMobileMsg,
          type: 'error'
        });
        return;
      }
      this.$refs.memberForm.validate(valid => {
        if (valid) {
          update(_this.memberForm).then(response => {
            if (response.code == 0) {
              this.$message({
                message: response.message,
                type: 'success'
              });
              this.dialogVisible = false;
              _this.refresh();
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          });
        }
      });
    },
    openAdd () {
      var roles = [];
      var allRoles = this.allRoles;
      allRoles.forEach(function (a) {
        if(a.status == 1){
          roles.push(a);
        }
      });
      this.roles = roles;
      this.memberForm = {
        id: '',
        userId: '',
        userName: '',
        mobile: '',
        email: '',
        status: 1,
        roleIds: []
      };
      this.dialogOption = 'create';
      this.dialogVisible = true;
    },
    isExistUserId () {
      var _this = this;
      if (!_this.memberForm.userId) {
        _this.passUserId = false;
        _this.passUserIdMsg = '请输入登陆ID,建议用名称的英文!';
        _this.$message({
          message: '请输入商户登陆ID,建议用名称的英文!',
          type: 'error'
        });
        return false;
      }
      findByUserId(_this.memberForm.userId).then(response => {
        if (response.code == 0 && response.data) {
          _this.$message({
            message: response.message,
            type: 'error'
          });
          _this.passUserId = false;
          _this.passUserIdMsg = response.message;
        }else{
          _this.passUserId = true;
          _this.passUserIdMsg = '';
        }
      });
    },
    saveMember (memberForm) {
      var _this = this;
      this.isDisable = true;
      setTimeout(() => {
        this.isDisable = false;
      }, 2000);
      if (!_this.passUserId) {
        _this.$message({
          message: _this.passUserIdMsg,
          type: 'error'
        });
        return;
      }
      if (!_this.passMobile) {
        _this.$message({
          message: _this.passMobileMsg,
          type: 'error'
        });
        return;
      }
      if (!_this.memberForm.password) {
        this.$message({
          message: '请输入登陆密码,6-18位数字,字母组合',
          type: 'error'
        });
        return;
      }
      this.$refs.memberForm.validate(valid => {
        if (valid) {
          insert(_this.memberForm).then(response => {
            if (response.code == 0) {
              this.$message({
                message: response.message,
                type: 'success'
              });
              this.dialogVisible = false;
              _this.refresh();
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          });
        }
      });
    },
    updateStatus (row) {
      var status = '';
      if (row.status == 1) {
        status = 0;
      } else {
        status = 1;
      }
      updateStatus(row.userId, status).then(response => {
        if (response.code == 0) {
          this.$message({
            message: response.message,
            type: 'success'
          });
          this.refresh();
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      });
    },
    refresh () {
      var _this = this;
      queryMember(this.pageable.currentPage, this.pageable.pageSize).then(response => {
        if (response.code == 0) {
          _this.pageable = {
            currentPage: response.data.pageInfo.page,
            pageSize: response.data.pageInfo.pageSize,
            total: response.data.pageInfo.total
          };
          _this.members = response.data.data;
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      });
    }
  },
  created: function () {
    this.refresh();
    findAllRoles().then(response => {
      if (response.code == 0) {
        if (response.data) {
          this.allRoles = response.data;
        }
      }
    });
  }
};
</script>


